package handler

import (
	"context"
	"dashenwo.com/dashenwo/micro_srv/search_srv/configs"
	"dashenwo.com/dashenwo/micro_srv/search_srv/genpb"
	"dashenwo.com/dashenwo/micro_srv/search_srv/internal/model"
	"dashenwo.com/dashenwo/micro_srv/search_srv/internal/service"
	"encoding/json"
	"github.com/micro/go-micro/v2/errors"
	"github.com/micro/go-micro/v2/util/log"
	"github.com/olivere/elastic/v7"
	"math"
)

type Search struct {
	searchService *service.SearchService
}

func (s Search) User(ctx context.Context, req *genpb.SearchRequest,res *genpb.SearchUserResponse) error {
	s.searchService.User(req)
	log.Log("进入了查询用户的方法",req)
	return nil
}

func (s Search) Article(ctx context.Context,req *genpb.SearchRequest,res *genpb.SearchArticleResponse) error  {
	log.Log("入口Search.Article")
	data, err := s.searchService.Article(req)
	if err!=nil{
		log.Log("查询时发生错误",err)
	}
	res.PageInfo = ResToPageInfo(data,req);
	if data.Hits.TotalHits.Value > 0 {
		for _, hit := range data.Hits.Hits {
			var t model.ArticleModel
			souceByte, _ :=  hit.Source.MarshalJSON();
			log.Log(hit.Fields)
			err := json.Unmarshal(souceByte, &t)
			if err != nil {
				// Deserialization failed
			}
			res.List = append(res.List, &t)
			log.Log("Tweet by %s: %s\n", t.Id, t.Content)
		}
	} else {
		return errors.New("com.dashenwo.srv.search","每页查询到数据",400)
	}
	// 解析数据赋值
	log.Log(data.TotalHits())
	return nil
}

func NewSearchHandler(searchService *service.SearchService) *Search {
	return &Search{
		searchService: searchService,
	}
}

func ResToPageInfo(result *elastic.SearchResult,req *genpb.SearchRequest) *model.PageModel {
	var (
		Size int32
		TotalCount int32
		Page int32
		TotalPage int32
	)

	// 获取每页显示数量
	if req.Size==0{
		Size = int32(configs.AppConf.Size)
	}else{
		Size = int32(configs.AppConf.Size)
	}
	// 获取总数据量
	TotalCount = int32(result.TotalHits())
	// 获取当前页数
	if req.Page>0{
		Page = req.Page
	}else{
		Page = 1;
	}
	log.Log(TotalCount,Size)
	v := float64(TotalCount) / float64(Size);
	// 计算总页数
	TotalPage = int32(math.Ceil(v))
	// 返回结果
	return &model.PageModel{
		Size: Size,
		Page: Page,
		TotalPage: TotalPage,
		TotalCount: TotalCount,
	}
}